package com.example.spring_aop.proxy.cglib;

import com.example.spring_aop.proxy.cglib.UserService;
import com.example.spring_aop.proxy.static_model.User;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @className: CglibProxy
 * @author: 芃
 * @description:
 * @date: 2024/12/30 14:45
 */
public class CglibProxy {
    public static void main(String[] args) {
        UserService userService = new UserService();

        Enhancer enhancer = new Enhancer();
        enhancer.setClassLoader(CglibProxy.class.getClassLoader());
        enhancer.setSuperclass(userService.getClass());

        MethodInterceptor interceptor = new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("执行Cglib的日志功能");
                Object ret = method.invoke(userService, objects);
                System.out.println("测试执行时间");
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-HH-mm HH:mm:ss");
                String date = simpleDateFormat.format(new Date());
                System.out.println("Cglib动态代理执行时间 ： " + date);
                System.out.println();
                return ret;
            }
        };

        enhancer.setCallback(interceptor);

        UserService userServiceProxy = (UserService) enhancer.create();
        userServiceProxy.login("朱意芃", "123456");
        userServiceProxy.register(new User("小豆", "654321"));
    }
}
